package cn.doctor.assistant.pad.ui.zhuanzhen;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.doctor.assistant.pad.R;
import cn.doctor.assistant.pad.api.zhuanzhen.TransferApi;
import cn.doctor.assistant.pad.api.zhuanzhen.TransferResponse;
import cn.doctor.assistant.pad.base.BaseFragment;
import cn.doctor.assistant.pad.base.ResultCallback;
import cn.doctor.assistant.pad.entity.PageInfo;
import cn.doctor.assistant.pad.entity.TransferBean;
import cn.doctor.assistant.pad.ui.UI;

/**
 * Created by jiaolf on 2016/4/6.
 */
public class TransferListFragment extends BaseFragment {

    @InjectView(R.id.edit_search)
    EditText editSearch;
    @InjectView(R.id.btn_search_clear)
    ImageButton btnSearchClear;
    @InjectView(R.id.btn_search)
    Button btnSearch;
    @InjectView(R.id.layout_search)
    LinearLayout layoutSearch;
    @InjectView(R.id.listview)
    ListView listview;
    @InjectView(R.id.listview_search)
    ListView listviewSearch;
    @InjectView(R.id.text_info_bottom_count)
    TextView textInfoBottomCount;

    @InjectView(R.id.text_info_bottom_total_page)
    TextView textInfoBottomTotalPage;
    @InjectView(R.id.text_info_bottom_current_page)
    TextView textInfoBottomCurrentPage;
    @InjectView(R.id.btn_bottom_previous_page)
    Button btnBottomPreviousPage;
    @InjectView(R.id.btn_bottom_next_page)
    Button btnBottomNextPage;

    int isTransfer;//  1 - 初始化（未转诊）2 - 已转诊
    private List<TransferBean> listDatas = new ArrayList<>();
    private List<TransferBean> listSearchDatas = new ArrayList<>();
    private TransferAdapter mAdapter;
    private TransferAdapter mSearchAdapter;

    private View rootView;

    final int PAGESIZE = 20; // 每页显示个数

    int totalCount; // 总条数
    int totalPage;  // 总页数
    int currentPage = 1; // 当前页

    int searchTotalCount; // 搜索结果的总条数
    int searchTotalPage; // 搜索结果的总页数
    int searchCurrPage = 1; // 搜索结果显示的当前页

    boolean isSearchState; // 处于搜索状态

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isTransfer = getArguments().getInt("isTransfer");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = LayoutInflater.from(activity).inflate(R.layout.fragment_transfer_list, container, false);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initialize();
    }

    void initialize() {
        if (listDatas.isEmpty()) {
            getTransfers();
        }

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UI.startActivity(TransferDetailActivity.class, "transfer", listDatas.get(position));
            }
        });
    }

    void getTransfers() {
        PageInfo pageInfo = new PageInfo();
        pageInfo.setPageSize(PAGESIZE);
        pageInfo.setCurrPage(currentPage);
        //XXX
        showProgress("加载中...");
        TransferApi.getTransfer(isTransfer, pageInfo, new ResultCallback<TransferResponse>() {
            @Override
            public void onSuccess(TransferResponse result) {
                stopProgress();
                if (result.getList().size() > 0) {
                    listDatas.clear();
                    listDatas.addAll(result.getList());

                    if (mAdapter == null) {
                        mAdapter = new TransferAdapter(activity, listDatas);
                        listview.setAdapter(mAdapter);
                    } else {
                        mAdapter.notifyDataSetChanged();
                    }

                } else {
                    showToast("无数据");
                }

                totalCount = result.getPageTotal();
                totalPage = (totalCount + PAGESIZE - 1) / PAGESIZE;
                setBottomBarText();
            }
        });
    }

    void searchTransfer(final String content) {
        showProgress("加载中...");
        TransferApi.searchTransfer(isTransfer, searchCurrPage, PAGESIZE, content, new ResultCallback<TransferResponse>() {
            @Override
            public void onSuccess(TransferResponse result) {
                stopProgress();
                if (result.getList().size() > 0) {
                    listSearchDatas.clear();
                    listSearchDatas.addAll(result.getList());

                    listview.setVisibility(View.GONE);
                    listviewSearch.setVisibility(View.VISIBLE);

                    if (mSearchAdapter == null) {
                        mSearchAdapter = new TransferAdapter(activity, listSearchDatas);
                        listviewSearch.setAdapter(mSearchAdapter);
                    } else {
                        mSearchAdapter.notifyDataSetChanged();
                    }
                } else {
                    showToast("没用搜索到" + content + "的相关结果");
                }

                searchTotalCount = result.getPageTotal();
                searchTotalPage = (searchTotalCount + PAGESIZE - 1 ) / PAGESIZE;
                setSearchBottomBarText();
            }
        });
    }

    void setBottomBarText() {
        // 总记录条数
        {
            String countStr = String.format("共有%d条记录", totalCount);
            SpannableStringBuilder ssb = new SpannableStringBuilder(countStr);
            ForegroundColorSpan span = new ForegroundColorSpan(getContext().getResources().getColor(R.color.assistant_theme_color));
            ssb.setSpan(span, 2, 2 + String.valueOf(totalCount).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textInfoBottomCount.setText(ssb);
        }

        // 总页数
        {
            String pageStr = String.format("共%d页", totalPage);
            SpannableStringBuilder ssb = new SpannableStringBuilder(pageStr);
            ForegroundColorSpan span1 = new ForegroundColorSpan(getContext().getResources().getColor(R.color.assistant_theme_color));
            int pageStrLength = String.valueOf(totalPage).length();
            ssb.setSpan(span1, 1, 1 + pageStrLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textInfoBottomTotalPage.setText(ssb);
        }

        // 当前页
        {
            String pageStr = String.format("当前第%d页", currentPage);
            SpannableStringBuilder ssb = new SpannableStringBuilder(pageStr);
            ForegroundColorSpan span1 = new ForegroundColorSpan(getContext().getResources().getColor(R.color.assistant_theme_color));
            int strLength = String.valueOf(currentPage).length();
            ssb.setSpan(span1, 3, 3 + strLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textInfoBottomCurrentPage.setText(ssb);
        }
    }

    void setSearchBottomBarText() {
        // 总记录条数
        {
            String countStr = String.format("共有%d条记录", searchTotalCount);
            SpannableStringBuilder ssb = new SpannableStringBuilder(countStr);
            ForegroundColorSpan span = new ForegroundColorSpan(getContext().getResources().getColor(R.color.assistant_theme_color));
            ssb.setSpan(span, 2, 2 + String.valueOf(searchTotalCount).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textInfoBottomCount.setText(ssb);
        }

        // 总页数
        {
            String pageStr = String.format("共%d页", searchTotalPage);
            SpannableStringBuilder ssb = new SpannableStringBuilder(pageStr);
            ForegroundColorSpan span1 = new ForegroundColorSpan(getContext().getResources().getColor(R.color.assistant_theme_color));
            int pageStrLength = String.valueOf(searchTotalPage).length();
            ssb.setSpan(span1, 1, 1 + pageStrLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textInfoBottomTotalPage.setText(ssb);
        }

        // 当前页
        {
            String pageStr = String.format("当前第%d页", searchCurrPage);
            SpannableStringBuilder ssb = new SpannableStringBuilder(pageStr);
            ForegroundColorSpan span1 = new ForegroundColorSpan(getContext().getResources().getColor(R.color.assistant_theme_color));
            int strLength = String.valueOf(searchCurrPage).length();
            ssb.setSpan(span1, 3, 3 + strLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            textInfoBottomCurrentPage.setText(ssb);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @OnClick({R.id.btn_search_clear, R.id.btn_search})
    public void onClick(View view) {
        switch (view.getId()) {
            //搜索
            case R.id.btn_search:
                String content = editSearch.getText().toString();
                if (!TextUtils.isEmpty(content)) {
                    isSearchState = true;
                    UI.hideKeyboard();
                    searchTransfer(content);
                }
                break;
            // 清空搜索
            case R.id.btn_search_clear:
                if (editSearch.getText().toString().equals("")) {
                    return;
                }

                isSearchState = false;
                editSearch.setText("");
                listviewSearch.setVisibility(View.GONE);
                listview.setVisibility(View.VISIBLE);
                setBottomBarText();
                break;

            // 上一页
            case R.id.btn_bottom_previous_page:
                if (isSearchState) {
                    if (searchCurrPage == 1) {
                        return;
                    }
                    searchCurrPage--;
                    searchTransfer(editSearch.getText().toString());
                } else {
                    if (currentPage == 1) {
                        return;
                    }
                    currentPage--;
                    getTransfers();
                }
                break;

            // 下一页
            case R.id.btn_bottom_next_page:
                if (isSearchState) {
                    if (searchCurrPage == searchTotalPage) {
                        return;
                    }
                    searchCurrPage++;
                    searchTransfer(editSearch.getText().toString());
                }else {
                    if (currentPage == totalPage) {
                        return;
                    }
                    currentPage++;
                    getTransfers();
                }
                break;
        }
    }
}
